<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="projectsName" placeholder="请输入名称" clearable size="small" prefix-icon="el-icon-search"
                    style="margin-bottom: 10px"/>
        </div>
        <div class="head-container">
          <el-tree :data="this.projectsOptions" :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick"/>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
<!--        数据-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="api接口名称" prop="apiName" label-width="100px">
            <el-input
              v-model="queryParams.apiName"
              placeholder="请输入api接口名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="请求方式" prop="method" label-width="90px">
            <el-select
              v-model="queryParams.method"
              placeholder="请选择"
              @change="resetInput()"
            >
              <el-option
                v-for="item in methodsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
<!--            <el-input-->
<!--              v-model="queryParams.method"-->
<!--              placeholder="请输入请求方式"-->
<!--              clearable-->
<!--              size="small"-->
<!--              @keyup.enter.native="handleQuery"-->
<!--            />-->
          </el-form-item>
          <el-form-item label="api的host" prop="host" label-width="90px">
            <el-input
              v-model="queryParams.host"
              placeholder="请输入api的host"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="api的地址" prop="apiurl" label-width="90px">
            <el-input
              v-model="queryParams.apiurl"
              placeholder="请输入api的地址"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:api:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:api:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:api:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:api:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="apiList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="api接口id" align="center" prop="apiId"/>
          <el-table-column label="api接口名称" align="center" prop="apiName" width="120"/>
          <el-table-column label="协议" align="center" prop="type" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.type==='http'" style="color: #825abe;font-weight: bold;font-size:18px">HTTP</span>
              <span v-if="scope.row.type==='https'" style="color: #d58a8a;font-weight: bold;font-size:18px">HTTPS</span>
            </template>

          </el-table-column>
          <el-table-column label="所属项目名称" align="center" prop="projectsName" width="120"/>
          <el-table-column label="请求方式" align="center" prop="method" >
            <template slot-scope="scope">
              <span v-if="scope.row.method==='get'" style="color: #1e82e5;font-weight: bold;font-size:18px">get</span>
              <span v-if="scope.row.method==='post'" style="color: #37a23e;font-weight: bold;font-size:18px">post</span>
              <span v-if="scope.row.method==='delete'" style="color: #de1130;font-weight: bold;font-size:18px">delete</span>
              <span v-if="scope.row.method==='put'" style="color: #ccce23;font-weight: bold;font-size:18px">put</span>
            </template>
          </el-table-column>
          <el-table-column label="api的host" align="center" prop="host" width="120"/>
          <el-table-column label="api的地址" align="center" prop="apiurl" width="120"/>
          <el-table-column label="超时时间" align="center" prop="timeout" />
          <el-table-column label="创建时间" align="center" prop="createTime" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:api:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate1(scope.row)"
              >详细信息</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:api:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <el-dialog :title="title"
               :visible.sync="open1" class="spec-dialog" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="API接口参数信息：" label-width="60">
            <br>
            <el-card class="box-card" style="margin-top:2px">
              <div style="width: 100%;margin-left: 10px;margin-top: 10px;">
                <b-code-editor v-model="this.form.requestParams"
                               :auto-format="true" :smart-indent="true"
                               :indent-unit="4"
                               :readonly=true
                               :data="this.form.requestParams"
                               :line-wrap="false" ref="editor">

                </b-code-editor>
                <br>
              </div>
            </el-card>
          </el-form-item>
        <el-form-item label="请求Body示例：" label-width="60">
          <br>
          <el-card class="box-card" style="margin-top:2px">
            <div style="width: 100%;margin-left: 10px;margin-top: 10px;">
              <b-code-editor v-model="this.form.requestBody"
                             :auto-format="true" :smart-indent="true"
                             :indent-unit="4"
                             :data="this.form.requestBody"
                             :readonly=true
                             :line-wrap="false" ref="editor">

              </b-code-editor>
              <br>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item label="返回示例：" label-width="60">
          <br>
          <el-card class="box-card" style="margin-top:2px">
            <div style="width: 100%;margin-left: 10px;margin-top: 10px;">
              <b-code-editor v-model="this.form.returnExample"
                             :auto-format="true" :smart-indent="true"
                             :indent-unit="4"
                             :data="form.returnExample"
                             :readonly=true
                             :line-wrap="false" ref="editor">

              </b-code-editor>
              <br>
            </div>
          </el-card>
        </el-form-item>
      </el-form>
     </el-dialog>

    <!-- 修改Api接口管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" class="spec-dialog" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="api接口名称" prop="apiName">
          <el-input v-model="form.apiName" placeholder="请输入api接口名称" />
        </el-form-item>
        <el-form-item label="所属项目名称">
          <el-select
            v-model="form.projectsName"
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectsOptions"
              :key="item.projectsName"
              :label="item.projectsName"
              :value="item.projectsName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求方式" prop="method">
          <el-select v-model="form.method" placeholder="请选择请求方式">
            <el-option label="post" value="post" />
            <el-option label="get" value="get" />
            <el-option label="delete" value="delete" />
            <el-option label="put" value="put" />
          </el-select>
        </el-form-item>
        <el-form-item label="api的host" prop="host">
          <el-input v-model="form.host" placeholder="请输入api的host" />
        </el-form-item>
        <el-form-item label="api的地址" prop="apiurl">
          <el-input v-model="form.apiurl" placeholder="请输入api的地址" />
        </el-form-item>
        <el-form-item label="超时时间" prop="timeout">
          <el-input v-model="form.timeout" placeholder="请输入超时时间" />
        </el-form-item>
        <el-form-item label="API接口参数信息：" label-width="60">
          <br>
          <el-card class="box-card" style="margin-top:2px">
            <div style="width: 100%;margin-left: 10px;margin-top: 10px;">
              <b-code-editor v-model="form.requestParams"
                             :auto-format="true" :smart-indent="true"
                             :indent-unit="4"
                             :data="form.requestParams"
                             :line-wrap="false" ref="editor">

              </b-code-editor>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item label="请求Body示例" prop="requestBody" label-width="60">
          <br>
          <el-card class="box-card" style="margin-top:2px">
            <div style="width: 100%;margin-left: 10px;margin-top: 10px;">
              <b-code-editor v-model="form.requestBody"
                             :auto-format="true" :smart-indent="true"
                             :indent-unit="4"
                             :data="this.form.requestBody"
                             :line-wrap="false" ref="editor">

              </b-code-editor>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item label="返回示例" prop="returnExample" label-width="60">
          <br>
          <el-card class="box-card" style="margin-top:2px">
            <div style="width: 100%;margin-left: 10px;margin-top: 10px;">
              <b-code-editor v-model="form.returnExample"
                             :auto-format="true" :smart-indent="true"
                             :indent-unit="4"
                             :data="form.returnExample"
                             :line-wrap="false" ref="editor" height="300px">

              </b-code-editor>
              <br>
            </div>
          </el-card>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApi, getApi, delApi, addApi, updateApi, exportApi } from "@/api/system/api";
import { allProject} from "@/api/system/project";
import ListProject from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import 'vue-json-pretty/lib/styles.css';
import {invoke} from "@/api/testutil/testhttp";
export default {
  name: "Api",
  components: {ListProject},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树选项
      projectsOptions: undefined,
      projects :[],
      // 部门名称
      projectsName: undefined,
      // Api接口管理表格数据
      apiList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        apiName: null,
        projectsName: null,
        method: null,
        host: null,
        apiurl: null,
        timeout: null,
        requestParams: null,
        requestBody: null,
        returnExample: null,
      },
      methodsOptions: [
        {
          value: "get",
          label: "GET"
        },
        {
          value: "post",
          label: "POST"
        },
        {
          value: "put",
          label: "PUT"
        },
        {
          value: "delete",
          label: "DELETE"
        }],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "projectsName",
      },

    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTree();
    this.getDept();
  },
  methods: {
    /** 查询Api接口管理列表 */
    getList() {
      this.getTree();
      this.loading = true;
      listApi(this.queryParams).then(response => {
        this.apiList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        apiId: null,
        apiName: null,
        projectsName: null,
        method: null,
        host: null,
        apiurl: null,
        timeout: null,
        requestParams: null,
        requestBody: null,
        returnExample: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.apiId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Api接口管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const apiId = row.apiId || this.ids
      getApi(apiId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改Api接口";
      });
    },
    handleUpdate1(row) {
      this.reset();
      const apiId = row.apiId || this.ids
      getApi(apiId).then(response => {
        this.form = response.data;
        this.open1 = true;
        this.title = "Api接口详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          try {
              JSON.parse(this.form.requestParams);
              JSON.parse(this.form.requestBody);
              JSON.parse(this.form.returnExample);
              console.log(this.form);
              updateApi(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
          } catch (e) {
            console.log(e);
            window.alert("Json格式错误，访问被拒绝")
            return false;
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const apiIds = row.apiId || this.ids;
      this.$confirm('是否确认删除Api接口管理编号为"' + apiIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delApi(apiIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 查询项目下拉树结构 */
    getTree() {
      allProject().then((response) => {
        this.projectsOptions = response.rows;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      this.getTree();
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },  // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.projectsName = data.projectsName;
      this.getList();
    },
    getDept()
    {
      allProject().then((response) => {
        this.projects = response.rows;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有Api接口管理数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportApi(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    }
  }
};
</script>
<style lang="scss">
.spec-dialog .el-dialog__body {
  padding: 3px 30px;
  overflow-y: auto;
  height: calc(100vh - 140px);
}
</style>
